<?php
class Paysdk_Tenpay extends Paysdk
{
    protected $gateway_url    = 'https://gw.tenpay.com/gateway/pay.htm';
    protected $verify_notify_url = 'https://gw.tenpay.com/gateway/verifynotifyid.xml';
    private $gateway_method = 'POST';

    public function set_info($tmp_param)
    {
        $param = array(
        'partner' => $this->pay_config['partner'],
        'return_url' => $this->pay_config['return_url'],
        'notify_url' => $this->pay_config['notify_url'],
        'bank_type' => 'DEFAULT',
        'fee_type' => '1',
        'spbill_create_ip' => $this->get_client_ip(),

        'sign_type' => 'MD5',
        'service_version' => '1.0',
        'service_version' => '1.0',
        'input_charset' => 'utf-8',
        'sign_key_index' => '1',

        'time_start' => date("YmdHis"),
        );
        $tmp_param['total_fee'] *= 100;
        $this->param = array_merge($param, $tmp_param);
        $this->param['sign'] = $this->createSign($this->param);
        return $this;
    }

    /**
	*获取带参数的请求URL
	*/
    function getRequestURL() {

        $this->param['sign'] = $this->createSign($this->param);

        $reqPar = "";
        ksort($this->param);
        foreach($this->param as $k => $v) {
            if("spbill_create_ip" != $k ) {
                $reqPar .= $k . "=" . urlencode($v) . "&";
            } else {
                $reqPar .= $k . "=" . str_replace(".", "%2E", $v) . "&";
            }
        }

        //去掉最后一个&
        $reqPar = substr($reqPar, 0, strlen($reqPar)-1);

        $requestURL = $this->get_gateway_url() . "?" . $reqPar;

        return $requestURL;
    }

    /**
	*创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	*/
    function createSign($param) {
        $signPars = "";
        ksort($param);
        foreach($param as $k => $v) {
            if("" != $v && "sign" != $k) {
                $signPars .= $k . "=" . $v . "&";
            }
        }
        $signPars .= "key=" . $this->pay_config['key'];
        $sign = strtolower(md5($signPars));
        return $sign;
    }

    /**
	*是否财付通签名,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	*true:是
	*false:否
	*/	
    function verify_return() {
        $param = array_merge($_GET, $_POST);
        if (!$this->createSign($param) == strtolower($param['sign']))
        {
            return false;
        }
        return $this->check_notify($param['notify_id']);
    }
    
    public function verify_notify()
    {
        return $this->verify_return();
    }

    protected function check_notify($notify_id)
    {
        $this->gateway_url          = $this->verify_notify_url;
        $this->param['partner']     = $this->pay_config['partner'];
        $this->param['notify_id']   = $notify_id;
        $url = $this->getRequestURL();
        //通信对象
        $httpClient = new Paysdk_Tenpay_HttpClient();
        $httpClient->setTimeOut(5);
        //设置请求内容
        $httpClient->setReqContent($url);
        if(!$httpClient->call())
        {
            return false;
        }
        $result = $this->parsexml($httpClient->getResContent());
        //判断签名及结果
        //只有签名正确,retcode为0，trade_state为0才是支付成功
        if(strtolower($result['sign']) == $this->createSign($result) && $result["retcode"] == "0" && $result["trade_state"] == "0" && $result["trade_mode"] == "1" ) {
            $data['out_trade_no']   = $result['out_trade_no'];
            $data['transaction_id'] = $result['transaction_id'];
            //金额,以分为单位,如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
            $data['total_fee']      = (!empty($result['discount']) ? $result['total_fee'] + $result['discount'] : $result['total_fee'])/100;
            return $data;
        }
        return false;
    }

    function parsexml($content)
    {
        $xml = simplexml_load_string($content);
        $encode = $this->getXmlEncode($content);

        $data = array();
        if($xml && $xml->children()) {
            foreach ($xml->children() as $node){
                //有子节点
                if($node->children()) {
                    $k = $node->getName();
                    $nodeXml = $node->asXML();
                    $v = substr($nodeXml, strlen($k)+2, strlen($nodeXml)-2*strlen($k)-5);

                } else {
                    $k = $node->getName();
                    $v = (string)$node;
                }

                if($encode!="" && $encode != "UTF-8") {
                    $k = iconv("UTF-8", $encode, $k);
                    $v = iconv("UTF-8", $encode, $v);
                }

                $data[$k] = $v;
            }
        }
        return $data;
    }

    //获取xml编码
    function getXmlEncode($xml) {
        $ret = preg_match ("/<?xml[^>]* encoding=\"(.*)\"[^>]* ?>/i", $xml, $arr);
        if($ret) {
            return strtoupper ( $arr[1] );
        } else {
            return "";
        }
    }

    /**
	*显示处理结果。
	*@param $show_url 显示处理结果的url地址,绝对url地址的形式(http://www.xxx.com/xxx.php)。
	*/	
    function doShow($show_url) {
        $strHtml = "<html><head>\r\n" .
        "<meta name=\"TENCENT_ONLINE_PAYMENT\" content=\"China TENCENT\">" .
        "<script language=\"javascript\">\r\n" .
        "window.location.href='" . $show_url . "';\r\n" .
        "</script>\r\n" .
        "</head><body></body></html>";

        echo $strHtml;

        exit;
    }
}